/*
* ResourceBundle.hpp   
*/				       
#ifndef __RESOURCEBUNDLE_HPP
#define __RESOURCEBUNDLE_HPP

#include <fstream>
#include <string>
#include <map>
#include "ReadHandle.hpp"

namespace magus {
    
class ResourceBundle
{
private:
	typedef std::map<std::string, std::string> resource_map;
	std::string 	m_path; 		// resource file path
	resource_map 	m_res; 			// resource map
	bool			loaded;

public:
	ResourceBundle(std::string path) : m_path(path), loaded(false)
	{
		std::ifstream input(path.c_str());
		if (input) {
			std::string line;
			loaded = true;
			while (!input.eof())
			{
				std::getline(input, line);
				trimString(line);
				if (line.size() == 0) continue;
#if defined(__GNUC__) && (__GNUC__ < 3)
				if (line.compare("/", 0, 1) == 0) continue;
				if (line.compare("#", 0, 1) == 0) continue;
				if (line.compare(";", 0, 1) == 0) continue;
#else
				if (line.compare(0, 1, "/") == 0) continue;
				if (line.compare(0, 1, "#") == 0) continue;
				if (line.compare(0, 1, ";") == 0) continue;
#endif
				int pos = line.find_first_of(":");
				if (pos == -1) 
					continue;
				std::string key = line.substr(0, pos);
				std::string value = line.substr(pos+1);
				trimString(key);	
				toUpper(key);
				trimString(value);
				m_res.insert(std::make_pair(key, value));
			}
			input.close();
		}
	}
	
	~ResourceBundle() { }

	// bool operator for status check
	operator bool() { return loaded; }
	
	// get string value by key                          
	std::string getString(std::string key, std::string def_val = "")
	{
		toUpper(key);
		resource_map::iterator it = m_res.find(key);
		if (it != m_res.end()) 
		{
			return it->second;
		}
		return def_val;
	}                     
	
	// get int value by key
	int getInt(std::string key, int def_val = 0)
	{
		toUpper(key);
		resource_map::iterator it = m_res.find(key);
		if (it != m_res.end()) {
			std::string value = it->second;
			return atoi(value.c_str());
		}
		return def_val;
	}

	// get int value by key
	int getIntLimited(std::string key, int min_val, int max_val)
	{
		int val = getInt(key);
		if (val < min_val) {
			val = min_val;
		}else if (val > max_val) {
			val = max_val;
		}
		return val;
	}
	                            
	bool putString(std::string key, std::string value); 
	bool putInt(std::string key, int value);             
	
};

} // namespace magus

#endif  /* __RESOURCEBUNDLE_HPP */

//////////////////////////////////////////////////////////////////////////////
